package product;

import models.BaseModel;
import models.constants.DeletedStatus;
import product.merchant.ProductSpecMerchant;
import util.common.UStringUtil;

import javax.persistence.*;
import java.util.Date;
import java.util.List;

/**
 * 产品限购 设置
 * Created by buhaoba on 2016/10/11.
 */
@Entity
@Table(name = "product_limitations")
public class ProductLimitations extends BaseModel {


    /**
     * 限购信息
     */
    @JoinColumn(name = "limitations_id")
    @ManyToOne
    public Limitations limitations;


    /**
     * 产品详细信息
     */
    @JoinColumn(name = "product_spec_merchant_id")
    @ManyToOne
    public ProductSpecMerchant productSpecMerchant;

    /**
     * 创建时间
     */
    @Column(name = "created_at")
    public Date createdAt;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;


    public static Long countByLimitationsAndSpecMerchant(Long limitationsId , Long specMerchantId) {
        return ProductLimitations.count("deleted = ? and limitations.id = ? and productSpecMerchant.id = ?" , DeletedStatus.UN_DELETED , limitationsId , specMerchantId);
    }

    /**
     * 加载某一设置下的item列表
     * @param limitationsId
     * @return
     */
    public static List<ProductLimitations> loadProductLimitationsList(long limitationsId){
        return ProductLimitations.find(" limitations.id = ? and deleted = ?" ,limitationsId, DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * 删除
     * @param dels
     */
    public static void deleteItem(Integer[] dels){
        String sql = "update product_limitations set deleted = ? where id in (" + UStringUtil.concatStr(",", dels) + ")";
        em().createNativeQuery(sql).setParameter(1, DeletedStatus.DELETED.getValue()).executeUpdate();
    }

}
